<template>
  <!-- 冷铁需求详情表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="80%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            max-height="710"
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              label="计划编号"
              prop="processingOrderNumber"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品图号"
              prop="figureNumber"
              min-width="170"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品名称"
              prop="materialName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="生产日期"
              prop="planActualDate"
              min-width="100"
              show-overflow-tooltip
              align="center"
              :formatter="formatDate"
            />
            <el-table-column
              label="工序"
              prop="processesClassification"
              min-width="100"
              align="center"
            >
              <template #default="{ row }">
                {{ useDictionary("ProcessType", row.processesClassification) }}
              </template>
            </el-table-column>
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="生产批次号"
              prop="plannedBatch"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="上工序完成时间"
              prop="lastProcessFinshTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <!--<el-table-column label="计划人员" props="planUsers" min-width="180">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planUserIds'"
                  :rules="rules.sonplanUserIds"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-select
                    v-model="row.memberIds"
                    placeholder="请选择计划人员"
                    clearable
                    style="width: 100%"
                    @change="changePlanUser(row)"
                    filterable
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="1"
                  >
                    <el-option
                      v-for="item in memberList"
                      :key="item.id"
                      :label="`${item.memberName}`"
                      :value="item.memberId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>-->
            <el-table-column
              label="理论时长/分"
              prop="theoreticalTime"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="{ row }">
                {{ Math.ceil(row.theoreticalTime / 60) }}
              </template>
            </el-table-column>
            <el-table-column
              label="计划开始时间"
              prop="planBeginTime"
              min-width="220"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planBeginTime'"
                  :rules="rules.planBeginTime"
                  label-width="0"
                >
                  <el-date-picker
                    v-model="row.planBeginTime"
                    type="datetime"
                    placeholder="请选择计划开始时间"
                    style="width: 100%"
                    :disabled-date="disabledDate"
                    :disabled="props.isReadonly"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="计划结束时间"
              prop="planEndTime"
              min-width="220"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planEndTime'"
                  :rules="rules.planEndTime"
                  label-width="0"
                >
                  <el-date-picker
                    v-model="row.planEndTime"
                    type="datetime"
                    :disabled-date="disabledDate"
                    placeholder="请选择计划结束时间"
                    style="width: 100%"
                    :disabled="props.isReadonly"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          v-if="formData.details.length > 0"
          @click="handleSubmit"
          >提 交</el-button
        >
        <!--<el-button
          type="primary"
          :loading="loading"
          v-if="formData.details.length > 0"
          @click="save"
          >保 存</el-button
        >-->
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "TIMEADJUST",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    Object.assign(formData.details, newVal);
  }
);
const sonTimeEnd = (rule: any, value: any, callback: any) => {
  formData.details.forEach((item) => {
    if (item.planBeginTime !== "") {
      if (value < item.planBeginTime) {
        callback(new Error("结束时间不能小于开始时间!"));
      } else {
        callback();
      }
    }
  });
};

const rules = reactive({
  planBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
  ],
  planEndTime: [
    { required: true, message: "请选择计划结束时间", trigger: "change" },
    {
      validator: sonTimeEnd,
      trigger: "change",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  details: [],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
}

const loading = ref(false);
//提交
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "计划时间修改";
      await request({
        url: "/mes/mesplanworkingform/adjustTimeSave",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
//保存
function save() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派保存";
      await request({
        url: "/mes/mesplanworkingform/userAssign",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};
</script>
